package server.mapper;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import server.HttpServlet;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MappedContext<String,Object> extends HashMap {


    /**
     * 加载解析server.xml,context标签
     */
    public Map loadServlet() throws DocumentException {
        MapperWrapper<String,Object> mapperWrapper= new MapperWrapper<String,Object>();
        Map mapWrapper = mapperWrapper.loadServlet();
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(resourceAsStream);
        // name="lagou" path="/demo"
        try {
            // //lagouServlet  /lagou
            for(java.lang.Object key:mapWrapper.keySet()){
                String url = (String) mapWrapper.get(key).toString();//  /lagou
                String servletName = (String) key.getClass().getSimpleName();

                Element rootElement = document.getRootElement();
                //List<Element> selectNodes = rootElement.selectNodes("//context");
                Element element = (Element)rootElement.selectSingleNode("//context");

                //for (int i = 0; i < selectNodes.size(); i++) {
                    //Element element = selectNodes.get(i);
                    String path = (String) element.attributeValue("path");// /demo
                    String name = (String) element.attributeValue("name");// lagou
                    if(servletName.equals("LagouServlet")){
                        this.put("/demo"+url,key);
                    }else if(servletName.equals("LagouServlet1")){
                        this.put("/demo1"+url,key);
                    }

               // }

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }
}
